﻿using NPOI.HSSF.UserModel;
using OMG.Fill.Potato.Model.Ent;
using OMG.Fill.Potato.Services;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Http;
namespace OMG.Fill.Potato.Model.UI.Controllers
{
    public class PotProsecutionController : ApiController
    {
        PotProsecutionServices potProsecutionServices = new PotProsecutionServices();
        
        //[ApiActionAuthorize("获取马铃薯生产经营实体及相关情况分页列表对象操作")]
        //[ApiActionException]
        public Pager<List<PotProsecutionEntity>> PostPageList(PotProsecutionQuery query)
        {
            return potProsecutionServices.GetPageList(query);
        }
        //[ApiActionAuthorize("新增马铃薯生产经营实体及相关情况指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Post(PotProsecutionEntity model) {
            return potProsecutionServices.AddInfo(model);
        }
        //[ApiActionAuthorize("修改马铃薯生产经营实体及相关情况指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Put(PotProsecutionEntity model)
        {
            return potProsecutionServices.UpdateInfo(model);
        }
        //[ApiActionAuthorize("删除马铃薯生产经营实体及相关情况指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Delete(string id)
        {
            return potProsecutionServices.DeleteInfo(id);
        }
        //[ApiActionAuthorize("获取马铃薯生产经营实体及相关情况指定对象操作")]
        //[ApiActionException]
        public ResResult<PotProsecutionEntity> Get(string ReportId)
        {
            return potProsecutionServices.GetModel(ReportId);
        }
        public ResResult<ProsecutionFillModel> Get(string AreaCode,string FillInYear)
        {
            return potProsecutionServices.GetModel(AreaCode,FillInYear);
        }

        public ResResult<List<List<AllYearStatisModel>>> GetAllYearStatisList(string AreaCode)
        {
            return potProsecutionServices.GetAllYearStatisList(AreaCode);
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public MemoryStream Method(string AreaCode, string FillInYear)
        {
            FileStream file = null;
            MemoryStream ms = new MemoryStream();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotDownload.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("PotProsecution") as HSSFSheet;//读取模板所在sheet位置
            PotProsecutionEntity pageModel = potProsecutionServices.GetModel(AreaCode, FillInYear).model.DataModel;//数据获取
            try
            {
                if (sheet != null)
                {
                    HSSFRow row = (HSSFRow)sheet.GetRow(4);//读取模板第5行
                    var style = row.GetCell(3).CellStyle;//读取模板第5行第4单元格样式并保存
                    row.GetCell(3).CellStyle = style;//对第5行第4单元格设置原来样式
                    if (pageModel != null)
                    {
                        HSSFRow datarow1 = (HSSFRow)sheet.GetRow(4);
                        datarow1.GetCell(3).SetCellValue(pageModel.MarketNum == null ? "" : pageModel.MarketNum.ToString());
                        datarow1.GetCell(3).CellStyle = style;

                        HSSFRow datarow2 = (HSSFRow)sheet.GetRow(5);
                        datarow2.GetCell(3).SetCellValue(pageModel.CdxMarket == null ? "" : pageModel.CdxMarket.ToString());
                        datarow2.GetCell(3).CellStyle = style;

                        HSSFRow datarow3 = (HSSFRow)sheet.GetRow(6);
                        datarow3.GetCell(3).SetCellValue(pageModel.ZypfMarket == null ? "" : pageModel.ZypfMarket.ToString());
                        datarow3.GetCell(3).CellStyle = style;

                        HSSFRow datarow4 = (HSSFRow)sheet.GetRow(7);
                        datarow4.GetCell(3).SetCellValue(pageModel.QyxzhpfMarket == null ? "" : pageModel.QyxzhpfMarket.ToString());
                        datarow4.GetCell(3).CellStyle = style;

                        HSSFRow datarow5 = (HSSFRow)sheet.GetRow(8);
                        datarow5.GetCell(3).SetCellValue(pageModel.FruCompanyNum == null ? "" : pageModel.FruCompanyNum.ToString());
                        datarow5.GetCell(3).CellStyle = style;

                        HSSFRow datarow6 = (HSSFRow)sheet.GetRow(9);
                        datarow6.GetCell(3).SetCellValue(pageModel.ZzNum_country == null ? "" : pageModel.ZzNum_country.ToString());
                        datarow6.GetCell(3).CellStyle = style;

                        HSSFRow datarow7 = (HSSFRow)sheet.GetRow(10);
                        datarow7.GetCell(3).SetCellValue(pageModel.ZzNum_pro == null ? "" : pageModel.ZzNum_pro.ToString());
                        datarow7.GetCell(3).CellStyle = style;

                        HSSFRow datarow8 = (HSSFRow)sheet.GetRow(11);
                        datarow8.GetCell(3).SetCellValue(pageModel.ZzNum_city == null ? "" : pageModel.ZzNum_city.ToString());
                        datarow8.GetCell(3).CellStyle = style;

                        HSSFRow datarow9 = (HSSFRow)sheet.GetRow(12);
                        datarow9.GetCell(3).SetCellValue(pageModel.ZzNum_county == null ? "" : pageModel.ZzNum_county.ToString());
                        datarow9.GetCell(3).CellStyle = style;

                        HSSFRow datarow10 = (HSSFRow)sheet.GetRow(13);
                        datarow10.GetCell(3).SetCellValue(pageModel.ZzNum_other == null ? "" : pageModel.ZzNum_other.ToString());
                        datarow10.GetCell(3).CellStyle = style;

                        HSSFRow datarow11 = (HSSFRow)sheet.GetRow(15);
                        datarow11.GetCell(3).SetCellValue(pageModel.HzNum == null ? "" : pageModel.HzNum.ToString());
                        datarow11.GetCell(3).CellStyle = style;

                        HSSFRow datarow12 = (HSSFRow)sheet.GetRow(16);
                        datarow12.GetCell(3).SetCellValue(pageModel.HznhNum == null ? "" : pageModel.HznhNum.ToString());
                        datarow12.GetCell(3).CellStyle = style;

                        HSSFRow datarow13 = (HSSFRow)sheet.GetRow(17);
                        datarow13.GetCell(3).SetCellValue(pageModel.NmhzArea == null ? "" : string.Format("{0:N2}", pageModel.NmhzArea));
                        datarow13.GetCell(3).CellStyle = style;

                        HSSFRow datarow30 = (HSSFRow)sheet.GetRow(18);
                        datarow30.GetCell(3).SetCellValue(pageModel.HzlzArea == null ? "" : string.Format("{0:N2}", pageModel.HzlzArea));
                        datarow30.GetCell(3).CellStyle = style;

                        HSSFRow datarow14 = (HSSFRow)sheet.GetRow(19);
                        datarow14.GetCell(3).SetCellValue(pageModel.NmhzYincome == null ? "" : string.Format("{0:N2}", pageModel.NmhzYincome));
                        datarow14.GetCell(3).CellStyle = style;
                        
                        sheet.CopyTo(workbook, "Sheet1", true, true);
                        workbook.Write(ms);
                        ms.Flush();
                        ms.Position = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString().Trim());
            }
            return ms;
        }

       /// <summary>
       /// 导出
       /// </summary>
       /// <param name="FillInYear"></param>
       /// <param name="AreaCode"></param>
        public void GetExcelData(string FillInYear, string AreaCode)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";            
            string strFileName = "（六）" + FillInYear + "-" + AreaName + "-马铃薯生产经营实体及相关情况.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));           
            curContext.Response.BinaryWrite(Method(AreaCode, FillInYear).GetBuffer());
            curContext.Response.End();
        }

      /// <summary>
      /// 导入
      /// </summary>
      /// <param name="ReportId"></param>
      /// <returns></returns>
        public ResResult<int> PostImportData(string ReportId)
        {          
            ResResult<int> obj = new ResResult<int>();
            ResResult<int> SingleObj = new ResResult<int>();
            HttpContext curContext = HttpContext.Current;
            HttpFileCollection files = curContext.Request.Files;
            ReportServices reportServices = new ReportServices();
            if (curContext.Request.Files.Count != 0)
            {
                HttpPostedFile upfile = files[0];
                if (upfile != null && upfile.ContentLength > 0)
                {
                    string temppath = curContext.Server.MapPath("~/App_Data/temppath");
                    if (!Directory.Exists(temppath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(temppath);//不存在则创建文件夹 
                    }
                    string filetype = Path.GetExtension(upfile.FileName);
                    string filenewName = Guid.NewGuid().ToString().Replace("-", "") + filetype;
                    string strpath = Path.Combine(temppath, filenewName);
                    upfile.SaveAs(strpath);
                    var model = potProsecutionServices.ExcelToModel(strpath, filetype);
                        model.ReportId = ReportId;
                        //判断list中是否初始化过报表
                        if (reportServices.CheckRepCount(ReportId,"T_PotProsecution"))
                        {
                            //没初始化过进来
                            potProsecutionServices.AddInfo(model);
                        }
                        else
                        {
                            potProsecutionServices.UpdateInfo(model);
                        }
                        obj.status = DefaultKey.SuccessResult; ;
                        obj.message = "数据导入成功！！";
                        reportServices.UpStatus(ReportId, "2", "");
                    

                    Directory.Delete(temppath, true);
                }
            }

            return obj;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        /// <returns></returns>
        public ResResult<List<ProsecutionStatisModel>> GetStatisListData(string AreaCode, string FillInYear)
        {
            return potProsecutionServices.getStatisListData(AreaCode, FillInYear);
        }

        public void GetStatisExcel(string AreaCode, string FillInYear)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = FillInYear + "年-" + AreaName + "-马铃薯生产经营及实体情况汇总表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            //curContext.Response.AppendHeader("Content-Disposition",
            //   "attachment;filename=" + strFileName);
            curContext.Response.BinaryWrite(loadStatis(AreaCode, FillInYear).GetBuffer());
            curContext.Response.End();
        }

        public MemoryStream loadStatis(string AreaCode, string FillInYear)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotStatisLoad.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件

            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet tempsheet = templateBook.GetSheet("PotProsecution") as HSSFSheet;//读取模板所在sheet位置
            List<ProsecutionStatisModel> pagelist = (List<ProsecutionStatisModel>)potProsecutionServices.getStatisListData(AreaCode, FillInYear).model;//数据获取            
            HSSFSheet sheet = CopyToSheet(tempsheet, pagelist);
            AreaServices areaServices = new AreaServices();
            string areaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            sheet.CopyTo(workbook, areaName, true, true);

            if (AreaCode.Equals("530000000000"))
            {
                var citys = areaServices.GetPrefectureList();
                foreach (string areacode in citys)
                {
                    List<ProsecutionStatisModel> citylist = potProsecutionServices.getAreaStatisList(areacode, FillInYear);
                    FileStream fm = new FileStream(templateName, FileMode.Open, FileAccess.Read);
                    HSSFWorkbook Book = new HSSFWorkbook(fm);
                    HSSFSheet temp = Book.GetSheet("PotProsecution") as HSSFSheet;
                    HSSFSheet sheet1 = CopyToSheet(temp, citylist);
                    string areaName1 = areaServices.GetByCodeModel(areacode).model.Name;
                    sheet1.CopyTo(workbook, areaName1, true, true);
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }



        public HSSFSheet CopyToSheet(HSSFSheet sheet, List<ProsecutionStatisModel> list)
        {
            HSSFRow row = (HSSFRow)sheet.GetRow(3);
            if (list.Count > 0)
            {
                for (int k = 0; k < list.Count; k++)
                {
                    HSSFRow datarow1 = (HSSFRow)sheet.CreateRow(3 + k);
                    datarow1.CreateCell(0).SetCellValue(list[k].AreaName == null ? "" : list[k].AreaName);
                    datarow1.CreateCell(1).SetCellValue(list[k].MarketNum == null ? "" : list[k].MarketNum.ToString());
                    datarow1.CreateCell(2).SetCellValue(list[k].CdxMarket == null ? "" : list[k].CdxMarket.ToString());
                    datarow1.CreateCell(3).SetCellValue(list[k].ZypfMarket == null ? "" : list[k].ZypfMarket.ToString());
                    datarow1.CreateCell(4).SetCellValue(list[k].QyxzhpfMarket == null ? "" : list[k].QyxzhpfMarket.ToString());
                    datarow1.CreateCell(5).SetCellValue(list[k].FruCompanyNum == null ? "" : list[k].FruCompanyNum.ToString());
                    datarow1.CreateCell(6).SetCellValue(list[k].ZzNum_country == null ? "" : list[k].ZzNum_country.ToString());
                    datarow1.CreateCell(7).SetCellValue(list[k].ZzNum_pro == null ? "" : list[k].ZzNum_pro.ToString());
                    datarow1.CreateCell(8).SetCellValue(list[k].ZzNum_city == null ? "" : list[k].ZzNum_city.ToString());
                    datarow1.CreateCell(9).SetCellValue(list[k].ZzNum_county == null ? "" : list[k].ZzNum_county.ToString());
                    datarow1.CreateCell(10).SetCellValue(list[k].ZzNum_other == null ? "" : list[k].ZzNum_other.ToString());
                    datarow1.CreateCell(11).SetCellValue(list[k].HzNum == null ? "" : list[k].HzNum.ToString());
                    datarow1.CreateCell(12).SetCellValue(list[k].HznhNum == null ? "" : list[k].HznhNum.ToString());
                    datarow1.CreateCell(13).SetCellValue(list[k].NmhzArea == null ? "" : string.Format("{0:N2}", list[k].NmhzArea));
                    datarow1.CreateCell(14).SetCellValue(list[k].HzlzArea == null ? "" : string.Format("{0:N2}", list[k].HzlzArea));
                    datarow1.CreateCell(15).SetCellValue(list[k].NmhzYincome == null ? "" : string.Format("{0:N2}", list[k].NmhzYincome));
                    for (int j = 0; j <= 15; j++)
                    {
                        datarow1.GetCell(j).CellStyle = row.GetCell(j).CellStyle;
                    }
                    if (k == (list.Count - 1))
                    {
                        // datarow1.RowStyle = Book.CreateCellStyle();
                        // datarow1.RowStyle.FillForegroundColor = HSSFColor.Blue.Index;
                    }
                }
            }
            return sheet;
        }

    }
}